package com.dkd.sbtz.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.dkd.common.core.domain.model.LoginUser;
import com.dkd.sbtz.domain.vo.spare.SpareBatchDTO;
import com.dkd.sbtz.domain.vo.spare.SpareVO;
import org.apache.ibatis.type.Alias;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.sbtz.domain.Spare;
import com.dkd.sbtz.service.ISpareService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;

/**
 * 备件库存Controller
 * 
 * @author xzj
 * @date 2025-09-03
 */
@Alias("Spare")
@RestController
@RequestMapping("/sbtz/spare")
public class SpareController extends BaseController
{
    @Autowired
    private ISpareService spareService;

    /**
     * 查询备件库存列表
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:spare:list')")
    @GetMapping("/list")
    public TableDataInfo list(Spare spare)
    {
        startPage();
        List<SpareVO> list = spareService.selectSpareList(spare);
        return getDataTable(list);
    }


//    @PreAuthorize("@ss.hasPermi('sbtz:spare:list')")
    @GetMapping("/lists")
    public TableDataInfo list(@RequestParam(required = false) String keyword) {
        startPage(); // 读取 pageNum/pageSize，启用 PageHelper
        List<Spare> list = spareService.list(keyword);
        return getDataTable(list);
    }

    /** POST /system/spare/ids  body: [1,2,3] */
//    @PreAuthorize("@ss.hasPermi('sbtz:spare:list')")
    @PostMapping("/ids")
    public AjaxResult listByIds(@RequestBody List<Long> ids) {
        return AjaxResult.success(spareService.listByIds(ids));
    }

    /**
     * 导出备件库存列表
     */
    @PreAuthorize("@ss.hasPermi('sbtz:spare:export')")
    @Log(title = "备件库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Spare spare)
    {
//        List<SpareVo> list = spareService.selectSpareList(spare);
//        ExcelUtil<Spare> util = new ExcelUtil<Spare>(SpareVo.class);
//        util.exportExcel(response, list, "备件库存数据");
    }

    /**
     * 获取备件库存详细信息
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:spare:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return success(spareService.selectSpareById(id));
//    }

    /** 详情：包含 variants 列表 */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(spareService.getDetail(id));
    }





    /**
     * 新增备件库存
     */
//    @PreAuthorize("@ss.hasPermi('sbtz:spare:add')")
//    @Log(title = "备件库存", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody Spare spare)
//    {
//        return toAjax(spareService.insertSpare(spare));
//    }


    /** 新增（含规格） */
    @PostMapping
    public AjaxResult add(@RequestBody SpareVO vo) {
        vo.setCreateBy(getUsername());
        spareService.insertSpareWithVariants(vo);
        return success();
    }


    /**
     * 修改备件库存
     */

    @PutMapping
    public AjaxResult edit(@RequestBody SpareVO vo) {
        vo.setUpdateBy(getUsername());
        spareService.updateSpareWithVariants(vo);
        return success();
    }



    /**
     * 删除备件库存
     */
    @PreAuthorize("@ss.hasPermi('sbtz:spare:remove')")
    @Log(title = "备件库存", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(spareService.deleteSpareByIds(ids));
    }



    /** 批量新增/更新（对接前端 <SpareBatchEditor> 的 submit） */
    @PreAuthorize("@ss.hasPermi('sbtz:spare:add')")
    @Log(title = "备件批量新增", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsert")
    public AjaxResult batch(@RequestBody @Valid List<SpareBatchDTO> body) {
        LoginUser lu = getLoginUser();
        String username = lu != null ? lu.getUsername() : "system";
        int[] r = spareService.batchUpsert(body, username);
        Map<String, Object> data = new HashMap<>();
        data.put("created", r[0]);
        data.put("updated", r[1]);
        data.put("variantsUpsert", r[2]);
        return AjaxResult.success("处理完成", data);
    }


    /**
     * 根据 spareId 获取厂商列表
     */
    @GetMapping("/vendors/{spareId}")
    public AjaxResult getVendorsBySpare(@PathVariable Long spareId) {
        List<String> vendors = spareService.selectVendorsBySpareId(spareId);
        return AjaxResult.success(vendors);
    }

    /**
     * 根据 spareId + vendor 获取规格列表
     */
    @GetMapping("/specs")
    public AjaxResult getSpecsBySpareVendor(
            @RequestParam("spareId") Long spareId,
            @RequestParam("vendor") String vendor) {
        List<String> specs = spareService.selectSpecsBySpareVendor(spareId, vendor);
        return AjaxResult.success(specs);
    }
}
